<?php
/**
 * Created by PhpStorm.
 * User: Maopy
 * Date: 2014/9/18
 * Time: 0:26
 */
namespace Common\Common;
class JSONHelper {
	/**
	 *  retInfo:根据状态json化返回值
	 *  @param status 执行的状态
	 * 			info 返回的信息
	 *  @return json字符串;
	 */

	const ERROR = 1;
	const SUCCESS =0;

	//下面都是错误码
	const TYPE_JSON = 10;

	const PARAS_ERROR = 400;         //参数错误
	const TEAM_EXIST = 401;          //球队已存在
	const LOGIN_ERROR = 402;         //登录验证未通过

	static function retInfo($status, $info = null, $type = self::TYPE_JSON) {
		if ($type == self::TYPE_JSON) {
			header('Content-Type: application/json');
		}
		$ret = array();
		if ($status) {
			$ret['status'] = JSONHelper::SUCCESS;
			$ret['data'] = $info;
		} else {
			$ret['status'] = JSONHelper::ERROR;
			$ret['data']['code'] = $info;
			$ret['data']['info'] = self::code2Info($info);
		}
		return json_encode($ret);
	}

	static function errorInfo($info = null, $type = self::TYPE_JSON)
	{
		if ($type == self::TYPE_JSON) {
			header('Content-Type: application/json');
		}

		$ret['status'] = JSONHelper::ERROR;
		$ret['data']['code'] = 300;
		$ret['data']['info'] = $info;

		echo json_encode($ret);
		exit();
	}

	static function echoJSON($status, $info = null, $type = self::TYPE_JSON) {
		echo self::retInfo($status, $info, $type);
		exit();
	}

	static function code2Info($code)
	{
		if(empty($code)){
			return "";
		}
		switch ($code) {
			case self::PARAS_ERROR:
				$ret = "参数错误";
				break;
			case self::TEAM_EXIST:
				$ret = "球队已存在";
				break;
			case self::LOGIN_ERROR:
				$ret = "用户名或密码错误";
				break;
			default:
				$ret = "未知错误";
				break;
		}
		return $ret;
	}
}
